package com.qing.springcloud.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.codec.Base62;
import cn.hutool.core.util.StrUtil;
import com.qing.springcloud.dto.user.UserDTO;
import com.qing.springcloud.exception.ExceptionTypeEnum;
import com.qing.springcloud.dao.UserDao;
import com.qing.springcloud.dto.user.UserLoginDTO;
import com.qing.springcloud.entity.User;
import com.qing.springcloud.exception.BusinessException;
import com.qing.springcloud.manger.UserChannelManager;
import com.qing.springcloud.model.UserStatus;
import com.qing.springcloud.service.LoginService;
import com.qing.springcloud.service.UserService;
import io.netty.channel.Channel;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author caozhipeng
 * @date 2025/7/11
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class LoginServiceImpl implements LoginService {

    private boolean isLoggedIn = false;

    @Autowired
    private  UserDao userDao;
    @NotNull
    private UserService userService;


    private final UserChannelManager channelManager;

    /**
     * 模拟用户登录
     */
    @Override
    public String login(UserLoginDTO dto) {
        User user = userDao.findByUsername(dto.getUsername())
                .orElseThrow(() -> new BusinessException(ExceptionTypeEnum.USER_NOT_EXIST));

        if (!StrUtil.equals(Base62.encode(dto.getPassword()), user.getPassword())) {
            throw new BusinessException(ExceptionTypeEnum.LOGIN_PASSWORD_ERROR);
        }
//      记录最后一次登录时间
        user.setLastLogin(new Date());
        userDao.updateById(user);

        // 第1步，先登录上
        StpUtil.login(user.getId());
        // 第2步，获取 Token  相关参数
        return StpUtil.getTokenValue();
    }

    /**
     * 模拟用户登出
     */
    public void logout() {
        StpUtil.logout();
    }

    /**
     * 检查用户是否登录
     * @return 登录状态
     */
    @Override
    public void checkLogin(String token) {
        if (!StpUtil.isLogin()) {
            throw new BusinessException(ExceptionTypeEnum.USER_NOT_LOGIN);
        }
    }

    /**
     * 刷新Token
     */
    @Override
    public void refreshToken() {

    }

    /**
     * 获取Token
     * @return Token
     */
    @Override
    public String getToken() {
        return "";
    }

    /**
     * 设置
     */
    @Override
    public void setToken(String token) {

    }

    /**
     * 清空Token
     */
    @Override
    public void clearToken() {

    }

    @Override
    public void setUserId(Long userId) {

    }

    @Override
    public Long getUserId() {
        return 0L;
    }

    @Override
    public UserDTO userOnline() {
        Long userId = StpUtil.getLoginIdAsLong();
        // 绑定用户到通道
        Channel channel = channelManager.getChannel(userId);
        if (channel != null) {
            channelManager.bindUserToChannel(userId, channel);
            channelManager.updateUserStatus(userId, UserStatus.ONLINE);
        }

        return userService.getUserInfo();
    }
}
